using System;
using System.Net;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using Argotic.Common;
using Argotic.Syndication;
using Srk.BetaseriesApi;

namespace RSS
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			try {
				IList<Show> shows = ShowSearch ("the office us");
				foreach (Show show in shows) {
					Console.WriteLine (show.Title);
					Console.WriteLine (show.Url);
					string ShowName = show.Title.Replace (" ", "-");
					TorrentDownload (ShowName);
				}
				
			} catch (Exception e) {
					Console.WriteLine (e.Message);
			}
		}
				
		public static IList<Show> ShowSearch (string ShowName)
		{
			BetaseriesClientFactory.Default = new BetaseriesClientFactory ("1330c9410051", "sLoTH/1.0.0.0", true);
			IBetaseriesSyncApi client = BetaseriesClientFactory.Default.CreateDefaultClient ();
			
			//client.Authenticate ("albator1932", "aspirin6"); // Identification sur le site
			
			IList<Show> shows = null;
			try {
				shows = client.SearchShows (ShowName);
			} catch (Exception ex) {
				Console.Error.WriteLine (ex.Message);
			}
			return shows;
		}
		
		public static void TorrentDownload (string ShowName) // Télécharge tous les torrents d'une série donnée
		{
			try {
				SyndicationResourceLoadSettings settings = new SyndicationResourceLoadSettings ();
				//settings.RetrievalLimit = 10;
	
				ShowName = ShowName.ToLower ();
				Uri feedUrl = new Uri ("http://www.dailytvtorrents.org/rss/show/" + ShowName + "?prefer=720&items=all");
				Console.WriteLine (feedUrl.ToString ());
				RssFeed feed = RssFeed.Create (feedUrl, settings);
	
				foreach (RssItem item in feed.Channel.Items) {				
					string TorrentName = item.Title.ToString ();
					TorrentName = "E:\\sLoTH\\" + TorrentName.Replace (' ', '_') + ".torrent";
					WebClient wc = new WebClient ();
					wc.DownloadFile (item.Link.ToString (),  @TorrentName);
					wc.Dispose ();
					Console.WriteLine ("Téléchargement de " + TorrentName + " terminé.");
					//Process.Start (Path.Combine (TorrentDir, TorrentName));
				}
			} catch (Exception e) {
				Console.WriteLine (e.Message);
			}
		}
	}
}